/*
 * @Description: 公共接口请求js
 * @Author: wangwangwang
 * @Date: 2020-07-01 14:36:58
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-02-23 11:10:47
 */
import request from '@/utils/request'

// 获取数据字典
export function getDicType(params) {
  return request({
    url: '/base/system/base/dictionary/get_detail_code',
    method: 'get',
    params,
  })
}
/**
 * @Description: 批量获取数据字典
 * @Param: 
 * @Author: wangwangwang
 */
export function getDicsType(params) {
  return request({
    url: '/base/system/base/dictionary/get_detail_codes',
    method: 'get',
    params,
  })
}
/**
 * @description  根据页面id获取按钮权限
 * @param {object} param 页面相关信息
 * @author fxg
 * @return {string} request 返回发送请求的格式
 */
export function getButtonList(params) {
  return request({
    url: '/base/system/function/limits/get_user_buttons',
    method: 'get',
    params
  })
}


export function getTables() {
  return request({
    url: '/base/system/base/dictionary/get_tables',
    method: 'get'
  })
}
export function getColumns(params) {
  return request({
    url: '/base/system/base/dictionary/get_columns',
    method: 'get',
    params,
  })
}
export function getIdList(data) {
  return request({
    url: '/base/system/base/organization/stations/get_id_list',
    method: 'post',
    data
  })
}

/*获取原物料强度等级*/
export function getListByTypeId(data) {
  return request({
    url: '/icps/system/sign/basics/namingRule/getListByTypeId',
    method: 'post',
    data
  })
}
/*获取登录用户供应商及合同*/
export function queryXinByUserid(data) {
  return request({
    url: '/icps/system/sign/dataCollection/contract/queryXinByUserid',
    method: 'post',
    data
  })
}
/*公司id查询供应商列表list*/
export function QueryAllSupplierBycompanyId(data) {
  return request({
    url: '/icps/system/sign/dataCollection/supplier/QueryAllSupplierBycompanyId',
    method: 'post',
    data
  })
}
/*根据供应商id查询合同list*/
export function queryListByUserID(data) {
  return request({
    url: '/icps/system/sign/dataCollection/contract/queryListByUserID',
    method: 'post',
    data
  })
}
/*获取用户数据权限*/
export function getUserAut(name) {
  let type = ''
  if (name == 'type') {//type=1不查站点管理数据
    type = '?type=1'
  }
  return request({
    url: '/icps/system/sign/basics/station/getUserAut' + type,
    method: 'post',
  })
}
/*获取某个组织的上级公司信息*/
export function get_simple_organization(params) {
  return request({
    url: '/base/system/base/organization/get_simple_organization',
    method: 'get',
    params
  })
}
/*根据站点查询合同list*/
export function getContractByStationId(data) {
  return request({
    url: '/icps/system/sign/dataCollection/contract/getContractByStationId',
    method: 'post',
    data
  })
}
/**
 * @Description: 根据公司ID获取公司下所有站点{id:}
 * @Param: 
 * @Author: wangwangwang
 * @param {*} params
 */
export function getStationByCompanyId(data) {
  return request({
    url: '/icps/system/sign/basics/station/getStationByCompanyId',
    method: 'post',
    data: data,
  })
}

/*获取公司列表*/
export function getcompany(params) {
  return request({
    url: '/base/system/base/organization/get_list_by_type',
    method: 'get',
    params
  })
}
/**
 * @Description: 根据CODE获取系统参数
 * @Param: 
 * @Author: wangwangwang
 * @param {*} params
 */
export function getSystemDetails(params) {
  return request({
    url: '/base/system/params/get_detail_by_code',
    method: 'get',
    params,
  });
}
/**获取用户列表!组织id+角色*/
export function get_simple_user_list(params) {
  return request({
    url: '/base/system/user/get_simple_user_list',
    method: 'get',
    params,
  })
}
/**获取用户列表!公司id+角色*/
export function get_simple_user_listBycompanyId(params) {
  return request({
    url: '/base/system/user/get_simple_user_listBycompanyId',
    method: 'get',
    params,
  })
}

/**
 * @Description: 附件限制条件
 * @Param: 
 * @Author: wangwangwang
 * @param {*} params
 */
export function getFileDetails(params) {
  return request({
    url: '/resource/accessory/getDetailBycode',
    method: 'get',
    params,
  });
}

/**
 * @Description: 消息列表
 * @Param: 
 * @Author: wangwangwang
 * @param {*} params
 */
export function getMessageList(data) {
  return request({
    url: '/message/system/message/logs/query_title_page',
    method: 'post',
    data,
  });
}

/**
 * @Description: 设置阅读状态
 * @Param: 
 * @Author: wangwangwang
 * @param {*} params
 */
export function setReadType(params) {
  return request({
    url: '/message/system/message/logs/read',
    method: 'get',
    params,
  });
}

import { getUserInfo } from "@/utils/auth.js";
/*获取组织用户树----开始*/
export async function orgUserTree(companyId) {
  let treearr = []//组织树
  let userArr = []//人员
  let organizationUser = []
  await request({//组织树
    url: '/base/system/base/organization/query_page',
    method: 'post',
    data: {
      page: 1,
      pageSize: 10000,
    }
  }).then(res => {
    console.log(JSON.parse(JSON.stringify(res.data)))
    treearr = res.data.data.map(res => {
      let obj = {
        id: res.id,
        parentId: res.parentId,
        name: res.name,
        type: 'org',
        typeId: res.typeId
      }
      return obj
    })
  })
  await request({//人员
    url: '/base/system/user/queryPage',
    method: 'post',
    data: {
      page: 1,
      pageSize: 999999,
      userEentrance: "entrance_manager"
    }
  }).then(res2 => {
    let arr = []
    res2.data.data.find(res => {
      let obj = {
        id: res.id,
        organizationId: res.organizationId,
        name: res.name,
        type: 'user',
        signatureImg: res.signatureImg,
      }
      arr.push(obj)
    })
    userArr = arr
  })
  console.log(userArr);
  for (let v in treearr) {
    let childrenArr = []
    for (let i in userArr) {
      if (treearr[v].id == userArr[i].organizationId) {
        childrenArr.push(userArr[i])
      }
    }
    if (childrenArr.length > 0) {
      treearr[v].children = childrenArr
    }
    if (!treearr.some(item => (item.parentId == treearr[v].id)) && treearr[v].type == 'org' && !treearr[v].children) {
      treearr[v].disabled = true
    }
  }
  organizationUser = formatTreeData(
    treearr,
    "id",
    "parentId",
    "children",
    "parent_id"
  );
  let UserInfo = await getUserInfo();
  if (!companyId) {
    companyId = UserInfo.companyId
  }
  if (UserInfo.adminStatus == 0) {//非admin账号只显示自己的公司组织或者传入的公司id组织
    console.log(JSON.parse(JSON.stringify(organizationUser)), companyId)
    organizationUser = [findBFS(organizationUser, companyId)]
  } else {//如果是admin就把第一层或第二层是公司得对象取出来组成新的公司开头的组织数组
    let arr = []
    organizationUser.forEach((v) => {
      if (v.typeId && v.typeId == '19da56b9e85648059e3cf1e7da497da4') {
        arr.push(v)
      } else if (v.children) {
        v.children.forEach((v2) => {
          if (v2.typeId && v2.typeId == '19da56b9e85648059e3cf1e7da497da4') {
            arr.push(v2)
          }
        })
      }
    })
    organizationUser = arr
  }
  if (organizationUser[0] == null) {
    organizationUser = []
  }
  console.log(JSON.parse(JSON.stringify(organizationUser)))
  return organizationUser
}
function formatTreeData(source, id, parentId, children, firstLayer) {
  const cloneData = JSON.parse(JSON.stringify(source))
  if (cloneData.length) {
    return cloneData.filter(father => {
      const fathercopy = father
      let branchArr = cloneData.filter(child => father[id] === child[parentId])
      if (father.children) {
        branchArr = [...father.children, ...branchArr]
      }
      if (branchArr.length > 0) {
        fathercopy[children] = branchArr
      }
      return father[parentId] === firstLayer
    })
  }
  return []
}
//数组集筛选满足条件的对象
function findBFS(objects, id) {
  const queue = JSON.parse(JSON.stringify(objects))
  while (queue.length) {
    const o = queue.shift()
    if (o.id == id) {
      return o
    }
    queue.push(...(o.children || []))
  }
}
/*获取组织用户树----结束*/
/**查询当前账号权限可看公司+自己公司拼接后去重 
 * @param {Boolean} type false传了就取外部公司, true传了就取外部公司
*/
export async function permissionsCompanyList(type) {
  let arrList = []
  let UserInfo = await getUserInfo();
  if (UserInfo.adminStatus == 0) {//非admin账号
    arrList.push({ id: UserInfo.companyId, name: UserInfo.companyName, organizationType: '19da56b9e85648059e3cf1e7da497da4' })//当前账号默认为内部公司
    await getUserAut().then((res) => {
      if (res.data?.companyList?.length > 0) {
        arrList = [...arrList, ...res.data.companyList]
      }
    });
    let map = new Map();
    for (let item of arrList) {
      if (!map.has(item.id)) {
        map.set(item.id, item);
      }
    }
    arrList = [...map.values()];
    //type传了就取外部公司
    if (type) {
      arrList = arrList.filter((v) => v.organizationType == 'b8f9367217ab43f8924cd6c08a9ba300')//只要外部公司
    } else {
      arrList = arrList.filter((v) => v.organizationType == '19da56b9e85648059e3cf1e7da497da4')//只要内部公司
    }
  } else {
    //type传了就取外部公司
    if (type) {
      /**通过typeId为外部公司类型id查询所有公司 */
      await getcompany({ typeId: "b8f9367217ab43f8924cd6c08a9ba300" }).then((res) => {
        arrList = res.data;
      });
    } else {
      /**通过typeId为内部公司类型id查询所有公司 */
      await getcompany({ typeId: "19da56b9e85648059e3cf1e7da497da4" }).then((res) => {
        arrList = res.data;
      });
    }
  }
  console.log(JSON.parse(JSON.stringify(arrList)), 'arrList')
  return arrList
}
/*公司列表+对应组织（有权限的）*/
export function getStationTree() {
  return request({
    url: '/icps/system/sign/basics/station/getStationTree',
    method: 'post'
  })
}
/**根据已有权限站点和去重后的公司+站点二级组织树，或只有站点 */
export async function getUserAutList(type) {
  let treeArr = []
  await getStationTree().then((res) => {
    treeArr = res.data;
  });
  if (type) {
    let site = []
    treeArr.forEach((v) => {
      site = [...site, ...v.children]
    })
    site.map((v) => {
      v.id = v.value
      v.name = v.label
    })
    return site
  } else {
    return treeArr
  }
}

/**根据权限组装组织树带人员的 */
export async function getPermissionsUserTree(type) {
  let arrList = []
  let UserInfo = await getUserInfo();
  if (UserInfo.adminStatus == 0) {//非admin账号
    arrList.push({ id: UserInfo.companyId, name: UserInfo.companyName, organizationType: '19da56b9e85648059e3cf1e7da497da4' })//当前账号默认为内部公司
    await getUserAut().then((res) => {
      if (res.data?.companyList?.length > 0) {
        if (type) {//true就只返回公司
          arrList = [...arrList, ...res.data.companyList]
        } else {
          arrList = [...arrList, ...res.data.companyList, ...res.data.departmentList, ...res.data.pointList]
        }
      }
    });
    let map = new Map();
    for (let item of arrList) {
      if (!map.has(item.id)) {
        map.set(item.id, item);
      }
    }
    arrList = [...map.values()];
    arrList.map((res) => res.selectable = false)
    return arrList
  }
}
/*根据组织id查询下级人员及组织树*/
export function getOrgznizationAndUsersTree(id) {
  return request({
    url: '/base/system/base/organization/getOrgznizationAndUsersTree?parentId=' + id,
    method: 'post',
  })
}
/*根据组织id查询下级带外部公司组织树*/
export function getOrgznizationTree(id) {
  return request({
    url: '/base/system/base/organization/getOrgznizationTree?parentId=' + id,
    method: 'post',
  })
}